package com.cx.model.ai.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.cx.entity.RestResp;
import com.cx.model.ai.entity.Chat;
import com.cx.model.ai.entity.LlmApiConfig;
import com.cx.model.ai.util.Const;
import okhttp3.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @program: pms
 * @author: cx
 * @description:
 * @create: 2025-03-18 15:13
 **/

@Service
public class LlmApi {


    @Resource
    private LlmApiConfig llmApiConfig;

    private final String  CHAT_URL = "/v1/workspace/cx/chat";

    public static void main(String[] args) throws IOException {

        String url = "http://localhost:3001/api/v1/workspace/cx/chat";
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS) // 设置连接超时时间为30秒
                .readTimeout(120, TimeUnit.SECONDS)    // 设置读取超时时间为30秒
                .writeTimeout(60, TimeUnit.SECONDS)   // 设置写入超时时间为30秒
                .build();
        Chat chat = new Chat("你叫什么名字", "chat");
        Request request = Const.buildHttpRequest(chat, url, "POST");
        Response response = client.newCall(request).execute();
        // 打印响应体的原始内容，用于调试
        String responseBody = response.body().string();
        System.out.println("Response Body: " + responseBody);
       // 检查响应体是否为空
        if (responseBody != null && !responseBody.isEmpty()) {
            try {
                JSONObject jsonObject = JSONObject.parseObject(responseBody);
                System.out.println(jsonObject.getString("textResponse"));
            } catch (com.alibaba.fastjson.JSONException e) {
                System.err.println("JSON 解析失败: " + e.getMessage());
            }
        } else {
            System.err.println("响应体为空");
        }
    }


    public RestResp doChat(Chat chat) {
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(40, TimeUnit.SECONDS) // 设置连接超时时间为30秒
                    .readTimeout(40, TimeUnit.SECONDS)    // 设置读取超时时间为30秒
                    .writeTimeout(40, TimeUnit.SECONDS)   // 设置写入超时时间为30秒
                    .build();
            String url = llmApiConfig.getUrl() +CHAT_URL ;
            Request request = Const.buildHttpRequest(chat, url, "POST");
            Response response = client.newCall(request).execute();
            // 打印响应体的原始内容，用于调试
            String responseBody = response.body().string();
            // 检查响应体是否为空
            if (responseBody != null && !responseBody.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(responseBody);

                String result = jsonObject.getString("textResponse");
                System.out.println(result);

                String tag = "</think>";
                int tagIndex = result.indexOf("</think>");
                String  resultResponse="";

                if(tagIndex != -1) {
                    resultResponse=result.substring(tagIndex + tag.length()).trim();
                    System.out.println(resultResponse);
                    return RestResp.success(resultResponse);
                } else {
                    // 标签不存在时返回空字符串（或根据需求调整）
                    resultResponse=result;

                    return RestResp.success(resultResponse);

                }


            } else {
                return RestResp.error("请求失败：" + "响应体为空");
            }
        } catch (Exception e) {
            return RestResp.error("请求失败：" + e.getMessage());
        }
    }
}